<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\Models\Columns;
use App\Models\Comment;
use core\utils\Dbbackup;


class CommonController extends Controller {
    public function getUser () {
        return Auth::user();
    }

    public function getActionName () {
        return explode('/', app('request')->route()->uri)[1];
    }

    public function lists () {
        $request = app('request');
        $module = $this->getActionName();
        $modelId = $this->getModelId($module);
        $keywords = '';

        if ($request->isMethod('get')) {
            $listArr = $this->getPageLists($module);
        } else {
            if (!empty($keywords = $request->keywords)) {
                $map[] = ['title', 'like', '%' . $keywords . '%'];
                $listArr = $this->getPageLists($module, $map);
            } else {
                $listArr = $this->getPageLists($module);
            }
        }

        $sortList = $this->getSortList($modelId);
        return ['list' => $listArr, 'sortList' => $sortList, 'keywords' => $keywords];
    }

    public function getModelId ($modelName) {
        $array = [1 => 'design', 2 => 'about', 3 => 'contact', 4 => 'blog'];
        $modelId = (int)implode(',', array_keys($array, $modelName));
        return $modelId;
    }

    /**
     * @param $modeName
     * @param array $where
     * @param string $order
     * @param int $pageSize
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function getPageLists ($modeName, $where = [], $order = 'ord asc, id desc', $pageSize = 12) {
        $lists = DB::table($modeName)->where($where)->orderByRaw($order)->paginate($pageSize);

        return $lists;
    }

    public function getCreate () {
        $sortList = $this->getSortList();
        return $sortList;
    }

    public function getInsert ($data) {
        $module = $this->getActionName();
        DB::table($module)->insert($data);
    }

    protected function getSortList () {
        $module = $this->getActionName();
        $modelId = $this->getModelId($module);
        $columns = Columns::find(1);
        $list = $columns->select(["colPid", "colId", "colTitle", "description", "ord", "model", DB::raw("concat(colPath,'-', colId) as bPath")])->where('modelid', $modelId)->get()->toArray();

        return $list;
    }

    public function getColumnsList ($module, $modelId) {
        $model = DB::table($module);
        $columns = Columns::find(1);
        $list = $columns->select(["colPid", "colId", "colTitle", "description", "ord", "model", DB::raw("concat(colPath,'-', colId) as bPath")])->where('modelid', $modelId)->get()->toArray();


        if (!empty($list)) {
            foreach ($list as $k => $v) {
                $list[$k]['count'] = count(explode('-', $v['bPath']));

                if (in_array($module, ['design', 'columns'])) {
                    $list[$k]['total'] = $model->where('colId', $v['colId'])->count();
                }

                if (in_array($module, ['blog'])) {
                    $list[$k]['total'] = $model->where('catid', $v['colId'])->count();
                }

                $str = '';

                if ($v['colPid'] != 0) {
                    for ($i = 0; $i < $list[$k]['count']; $i++) {
                        $str .= '&nbsp;&nbsp;&nbsp;&nbsp;';
                    }
                    $str .= '|-';
                }

                $list[$k]['space'] = $str;
            }
        }

        return $list;
    }

    public function getEdit ($id) {
        $module = $this->getActionName();
        $modelId = $this->getModelId($module);
        //        $columns = new Columns();
        $columns = Columns::find(1);
        //        $blog = Columns::first();
        //        dump($blog);
        $sortList = $columns->select(["colPid", "colId", "colTitle", "description", "ord", "model", DB::raw("concat(colPath,'-', colId) as bPath")])->where('modelid', $modelId)->get()->toArray();
        //        $blogs = $columns->first();
        //        dump($blog);

        //        foreach ($blogs as $blog) {
        //            dump($blog);
        //        }

        //        $sortList = $columns->sortList($module, $modelId);
        $vo = DB::table($module)->where('id', $id)->first();
        //        dump($sortList);

        //        return ['vo' => $vo, 'sortList' => $sortList];
        return compact('vo', 'sortList');
    }

    public function upload (Request $request) {
        if (!$request->isMethod('POST')) {
            return json_encode(['code' => 1, 'msg' => '非法请求']);
        }

        $files = $request->file("file");

        if ($files->isValid()) {
            $ext = $files->extension();
            $realPath = $files->path();
            $file_new_name = date('Y-m-d-H-i-s') . '-' . uniqid() . '.' . $ext; // "2020-01-27-03-39-35-5e2e5b779630b.jpeg"
            $bool = Storage::disk('uploads')->put($file_new_name, file_get_contents($realPath));

            if ($bool) {
                $result = ['code' => 0, 'msg' => '上传成功', 'data' => ['src' => $file_new_name]];
            } else {
                $result = ['code' => 1, 'msg' => '上传失败'];
            }
        } else {
            $result = ['code' => 1, 'msg' => '上传文件无效，请重新上传'];
        }
        return json_encode($result);
    }

    public function getUpdate ($data) {
        $module = $this->getActionName();
        $source = 'App\\Models\\' . ucfirst($module);
        $model = new $source();
        $pk = $model->getKeyName();
        $result = $model->where($pk, $data[$pk])->update($data);
        return $result;
    }

    public function remove ($id) {
        $module = $this->getActionName();
        $mod = DB::table($module);
        $result[] = [];

        foreach ($id as $v) {
            if (in_array($module, ['design', 'about', 'contact', 'blog', 'advs'])) {
                $thumb = $mod->where('id', $v)->pluck('smallimg');
                $this->delThumb($thumb[0]);
            }

            if (in_array($module, ['columns'])) {
                $result[] = $mod->where('colId', $v)->delete();
            } else {
                $result[] = $mod->where('id', $v)->delete();
            }

        }

        /*
        if ($result) {
            $this->success('删除成功', 'admin/' . $module . '/index');
        } else {
            $this->error('删除失败');
        }
        */
    }

    // 删除缩略图片
    public function delThumb ($thumb) {
        if ($thumb !== false) {
            //            $file = 'storeage' . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR . $thumb;
            //            dump($file);
            //            if (is_file($file)) {
            ////                unlink(storage_path('uploads' . DIRECTORY_SEPARATOR . $file));
            //                unlink($file);
            //            }
            Storage::delete($thumb);
        }
    }

    public function getCommentData ($module = 'design') {
        $request = app('request');
        $model = Comment::find(1);
        $keywords = '';
        $listArr = [];

        $field = ["id", "username", "author", "pid", "nid", "bid", "inputtime", "headimg", "email", "url", "module", "isreply", "ip", "content", "path", DB::raw("concat(path,'-',id) as bpath")];
        $where = [
            ['module', $module],
            ['isreply', '!=', 1]
        ];

        if ($request->isMethod('get')) {
            $listArr = $model->getCommentList($field, $where);
        } else {
            if (!empty($keywords = $request->keywords)) {
                $map[] = ['content', 'like', '%' . $keywords . '%'];
                $listArr = $model->getCommentList($field, $map);
            } else {
                $listArr = $model->getCommentList($field);
            }
        }

        return ['list' => $listArr, 'keywords' => $keywords];
    }

    public function mysqlcn(){
        return new Dbbackup(config('database.connections.mysql'));
    }

}
